package com.xsb.mvvmlibrary.network.interceptor

import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import okio.Buffer
import java.io.IOException
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets

/**
 *     author : 薛少博
 *     e-mail : xsb@zlhopesun.com
 *     time   : 2021/5/19
 *     desc   : 类说明
 */
class RetrofitInterceptor : Interceptor {
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request().newBuilder().addHeader("Authorization", "token").build()
        printRequestMessage(request)
        val response = chain.proceed(request)
        printResponseMessage(response)
        return response
    }

    /**
     * 请求参数日志打印
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private fun printParams(body: RequestBody?) {
        if (body != null) {
            val buffer = Buffer()
            try {
                body.writeTo(buffer)
                var charset = StandardCharsets.UTF_8
                val contentType = body.contentType()
                if (contentType != null) {
                    charset = contentType.charset(StandardCharsets.UTF_8)
                }
                val params = buffer.readString(charset)
                Log.e(TAG, "请求参数： | $params")
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

    /**
     * 打印请求消息
     *
     * @param request 请求的对象
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private fun printRequestMessage(request: Request?) {
        if (request == null) {
            return
        }
        Log.i(TAG, "Url   : " + request.url().url().toString())
        Log.i(TAG, "Method: " + request.method())
        Log.i(TAG, "Heads : " + request.headers())
        val requestBody = request.body()
        if (requestBody != null) {
            val buffer = Buffer()
            try {
                requestBody.writeTo(buffer)
                var charset = Charset.forName("UTF-8")
                val contentType = requestBody.contentType()
                if (contentType != null) {
                    charset = contentType.charset(StandardCharsets.UTF_8)
                }
                val params = buffer.readString(charset)
                Log.i(TAG, "params : $params")
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

    /**
     * 打印返回消息
     *
     * @param response 返回的对象
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private fun printResponseMessage(
        response: Response?
    ) {
        if (response == null || !response.isSuccessful) {
            return
        }
        val responseBody = response.body()
        val contentLength = responseBody!!.contentLength()
        val source = responseBody.source()
        try {
            source.request(Long.MAX_VALUE) // Buffer the entire body.
        } catch (e: IOException) {
            e.printStackTrace()
        }
        val buffer = source.buffer
        var charset: Charset? = null
        val contentType = responseBody.contentType()
        if (contentType != null) {
            charset = contentType.charset(StandardCharsets.UTF_8)
        }
        if (contentLength != 0L) {
            val result = buffer.clone().readString(charset)
            Log.i(TAG, "Response: $result")
        }
    }

    companion object {
        const val TAG = "NetLog"
    }
}
